package com.geeguo.ebuilder.core.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@Slf4j
public class DateUtils {

    private static final String[] parsePatterns = new String[] {
            "yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm",
            "yyyy-MM",
            "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss",
            "yyyy/MM/dd HH:mm",
            "yyyy/MM",
            "yyyy.MM.dd",
            "yyyy.MM.dd HH:mm:ss",
            "yyyy.MM.dd HH:mm",
            "yyyy.MM"
    };

    public static Date parseDate(String text) {
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(text, parsePatterns);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * date类型进行格式化输出（返回类型：String）
     */
    public static String dateFormat(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(date);
    }

    /**
     * date类型进行格式化输出（返回类型：String）
     */
    public static String dateTimeFormat(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    /**
     * 当前时间进行格式化输出
     *
     * @param pattern
     * @return
     */
    public static String nowFormat(String pattern) {
        Date date = new Date();
        if (pattern == null && "".equals(pattern)) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 获取当天开始时间
     */
    public static Date getDayBegin() {
        Calendar cal = Calendar.getInstance();
        //0点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        //0分
        cal.set(Calendar.MINUTE, 0);
        //0秒
        cal.set(Calendar.SECOND, 0);
        //0毫秒
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取当天结束时间
     */
    public static Date getDayEnd() {
        Calendar cal = Calendar.getInstance();
        //23点
        cal.set(Calendar.HOUR_OF_DAY, 23);
        //59分
        cal.set(Calendar.MINUTE, 59);
        //59秒
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    /**
     * 获取某个日期的开始时间
     */
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }

    /**
     * 获取某个日期的结束时间
     */
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return new Timestamp(calendar.getTimeInMillis());
    }

    /**
     * Date转换为LocalDate
     *
     * @param date
     */
    public static LocalDate dateToLocalDate(Date date) {
        if (date != null) {
            //An instantaneous point on the time-line.(时间线上的一个瞬时点。)
            Instant instant = date.toInstant();
            //A time-zone ID, such ZxingCodeUtil {@code Europe/Paris}.(时区)
            ZoneId zoneId = ZoneId.systemDefault();
            return instant.atZone(zoneId).toLocalDate();
        }
        return null;
    }

    /**
     * Date转换为LocalDateTime
     *
     * @param date
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        if (date != null) {
            //An instantaneous point on the time-line.(时间线上的一个瞬时点。)
            Instant instant = date.toInstant();
            //A time-zone ID, such ZxingCodeUtil {@code Europe/Paris}.(时区)
            ZoneId zoneId = ZoneId.systemDefault();
            return instant.atZone(zoneId).toLocalDateTime();
        }
        return null;
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDate
     */
    public static Date localDateToDate(LocalDate localDate) {
        if (localDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth());
            return calendar.getTime();
        }
        return null;
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        if (localDateTime != null) {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = localDateTime.atZone(zoneId);
            return Date.from(zdt.toInstant());
        }
        return null;
    }

    /**
     * 时间加减年数
     *
     * @param startDate 要处理的时间，Null则为当前时间
     * @param years     加减的年数
     * @return Date
     */
    public static Date dateAddYears(Date startDate, int years) {
        if (startDate == null) {
            startDate = new Date();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(startDate);
        c.set(Calendar.YEAR, c.get(Calendar.YEAR) + years);
        return c.getTime();
    }

    /**
     * 时间加减月数
     *
     * @param startDate 要处理的时间，Null则为当前时间
     * @param months    加减的月数
     * @return Date
     */
    public static Date dateAddMonths(Date startDate, int months) {
        if (startDate == null) {
            startDate = new Date();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(startDate);
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) + months);
        return c.getTime();
    }

    /**
     * 时间加减天数
     *
     * @param startDate 要处理的时间
     * @param days      加减的天数
     * @return Date
     */
    public static Date dateAddDays(Date startDate, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(startDate);
        c.add(Calendar.DAY_OF_MONTH, days);
        return c.getTime();
    }

    /**
     * 获取今年是哪一年
     */
    public static Integer getYear(Date date) {
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(Calendar.YEAR);
    }

    /**
     * 获取本月是哪一月
     */
    public static int getMonth(Date date) {
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取本月的开始时间
     */
    public static Date getBeginDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date) - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取本月的结束时间
     */
    public static Date getEndDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date) - 1, 1);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(getYear(date), getMonth(date) - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    /**
     * 获取上月的开始时间
     */
    public static Date getBeginDayOfLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date) - 2, 1);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取上月的结束时间
     */
    public static Date getEndDayOfLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date) - 2, 1);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(getYear(date), getMonth(date) - 2, day);
        return getDayEndTime(calendar.getTime());
    }

    /**
     * 获取下个月的开始时间
     */
    public static Date getBeginDayOfNextMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date), 1);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取下个月的结束时间
     */
    public static Date getEndDayOfNextMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(date), getMonth(date), 1);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(getYear(date), getMonth(date), day);
        return getDayEndTime(calendar.getTime());
    }

    /**
     * 获取本周的开始时间
     */
    public static Date getBeginDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            dayOfWeek += 7;
        }
        calendar.add(Calendar.DATE, 2 - dayOfWeek);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取本周的结束时间
     */
    public static Date getEndDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        int daysToAdd = 7 - dayOfWeek + 1;
        if (dayOfWeek == Calendar.SUNDAY) {
            daysToAdd = 0;
        }
        calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
        return getDayEndTime(calendar.getTime());
    }

    /**
     * 获取指定月份的开始时间
     */
    public static Date getBeginDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取指定月份的结束时间
     */
    public static Date getEndDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(year, month - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    /**
     * 获取指定年份的开始时间
     */
    public static Date getBeginDayOfYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, Calendar.JANUARY, 1);
        return getDayStartTime(calendar.getTime());
    }

    /**
     * 获取指定年份的结束时间
     */
    public static Date getEndDayOfYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, Calendar.DECEMBER, 31);
        return getDayEndTime(calendar.getTime());
    }
}